package com.cjm.one.order.handle;

import com.cjm.one.common.constant.RedisConstants;
import com.cjm.one.common.constant.SecurityConstants;
import com.cjm.one.goods.client.GoodsSKuClient;
import com.cjm.one.model.goods.dto.StockRevertDTO;
import com.cjm.one.model.order.entity.OrderInfo;
import com.cjm.one.model.order.entity.OrderItem;
import com.cjm.one.model.order.enums.OrderStatusEnum;
import com.cjm.one.order.mapper.OrderItemMapper;
import com.cjm.one.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class RedisDelayHandle {

    @Resource
    private GoodsSKuClient goodsSkuClient;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private OrderItemMapper orderItemMapper;
    @PostConstruct
    public void listener() {
        new Thread(() -> {
            RBlockingQueue<String> queue = redissonClient.getBlockingQueue(
                    RedisConstants.ORDER_CANCEL_DELAY_QUEUE);
            while (true) {
                try {
                    String orderId = queue.take();
                    log.info("开始处理超时订单：{}", orderId);
                    
                    // 获取订单关联的SKU
                    List<StockRevertDTO> skuIds = orderItemMapper.selectSkuIdsByOrder(Long.valueOf(orderId));
                    
                    // 双重检查订单状态
                    OrderInfo order = orderInfoService.getById(orderId);
                    if (order.getOrderStatus() == OrderStatusEnum.WAIT_PAY) {
                        // 关闭订单
                        orderInfoService.cancelOrder(orderId);
                        
                        // 回退库存（带版本控制）
                        if (!skuIds.isEmpty()) {
                            Boolean rows = goodsSkuClient.revertStock(skuIds, SecurityConstants.INNER).getData();
                            log.info("订单{}库存回退成功", orderId);
                        }
                    }
                } catch (Exception e) {
                    log.error("订单超时处理异常", e);
                }
            }
        }, "order-timeout-thread").start();
    }
}